<?php
namespace app\common\taglib;

use think\Session;
use think\template\TagLib;

//自定义标签库
class Html extends TagLib
{

    //定义标签列表
    protected $tags = [
        // 标签定义： attr 属性列表 close 是否闭合（0 或者1 默认1） alias 标签别名 level 嵌套层次
        'menu' => ['attr' => 'name,id'],
        'nav'  => ['attr' => 'id']
    ];

    //菜单标签
    public function tagMenu($tag, $content)
    {
        $admin_id = Session::has('admin.id') ? Session::get('admin.id') : 1;
        $name     = empty($tag['name']) ? 'menus' : $tag['name'];
        $id       = $tag['id'];
        $parseStr .= '<?php ';
        $parseStr .= '$rules = db("auth_group")->where("id",' . $admin_id . ')->value("rules");';
        $parseStr .= '$menus = db("auth_rule")->where("id","in",$rules)->order("sort")->select();';
        $parseStr .= '$menus = \app\admin\model\Admin::sonTree($menus);';
        $parseStr .= 'foreach($' . $name . ' as $' . $id . '): ';
        $parseStr .= '?>';
        // 循环体中的内容
        $parseStr .= $content;
        $parseStr .= '<?php endforeach; ?>';
        //dump($parseStr);die;
        if (!empty($parseStr)) {
            return $parseStr;
        }
        return;
    }

    //导航标签
    public function tagNav($tag, $content)
    {
        $v = $tag['id'] ? $tag['id'] : 'v';
        $parseStr = '<?php ';
        $parseStr .= '$navs = get_app_config("nav")["nav"]["nav"];asort($navs);';
        $parseStr .= '$module = strtolower(request()->module());';
        $parseStr .= '$controller = strtolower(request()->controller());';
        $parseStr .= '$action = strtolower(request()->action());';
        $parseStr .= 'foreach($navs as &$' . $v . '): ';
        $parseStr .= 'if(empty($'.$v.'["show"])){ unset($' . $v . '); continue;}';
        $parseStr .= '?>';
        $parseStr .= '<?php if(strtolower($'.$v.'["link"]) == $module."/".$controller."/".$action): ?>';
        $parseStr .= '<?php $'.$v.'["active"] = true; else: $'.$v.'["active"] = false; ?>';
        $parseStr .= '<?php endif; ?>';
        $parseStr .= '<?php $'.$v.'["link"] = url($'.$v.'["link"]); ?>';
        $parseStr .= $content;
        $parseStr .= '<?php endforeach; ?>';
        if (!empty($parseStr)) {
            return $parseStr;
        }
        return;
    }

}
